<template>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
        <template #header>
            <el-row :gutter="20">
                <el-col :span="12" :offset="0">物品管理</el-col>
                <!-- 添加添加物品按钮 -->
                <el-col :span="4" :offset="8">
                    <el-button type="primary" size="small" @click="handleAdd">添加物品</el-button>
                </el-col>
            </el-row>
        </template>
        <!-- card body -->
        <div>
            <el-table :data="itemList" v-loading="loading" style="width: 100%">
                <el-table-column fixed label="ID" prop="id" width="80"></el-table-column>
                <el-table-column label="名称" prop="name" width="100"></el-table-column>
                <el-table-column label="描述" prop="description" width="100"></el-table-column>
                <el-table-column label="创建人 ID" prop="created_by" width="100"></el-table-column>
                <el-table-column fixed="right" label="操作" width="150">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="handleEdit(scope.row)">修改</el-button>
                        <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 编辑对话框 -->
        <el-dialog title="编辑物品信息" v-model="dialogVisible" width="50%">
            <el-form :model="editForm" label-width="80px" :rules="rules" ref="editFormRef">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="editForm.name"></el-input>
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input type="textarea" v-model="editForm.description" rows="6"></el-input>
                </el-form-item>
                <el-form-item label="创建人 ID" prop="created_by">
                    <el-input v-model="editForm.created_by"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitEdit">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 添加对话框 -->
        <el-dialog title="添加物品" v-model="addDialogVisible" width="50%">
            <el-form :model="addForm" label-width="80px" :rules="rules" ref="addFormRef">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="addForm.name"></el-input>
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input type="textarea" v-model="addForm.description" rows="6"></el-input>
                </el-form-item>
                <el-form-item label="创建人 ID" prop="created_by">
                    <el-input v-model="addForm.created_by"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitAdd">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </el-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getItemList, deleteItem, updateItem, addItem } from '@/api/item'
import { ElMessage, ElMessageBox } from 'element-plus'

// 数据定义
const itemList = ref([])
const loading = ref(false)

const dialogVisible = ref(false)
const editFormRef = ref(null)
// 添加对话框显示状态
const addDialogVisible = ref(false)
// 添加表单引用
const addFormRef = ref(null)

// 编辑表单
const editForm = reactive({
    id: '',
    name: '',
    description: '',
    created_by: ''
})

// 添加表单
const addForm = reactive({
    name: '',
    description: '',
    created_by: ''
})

// 表单验证规则
const rules = {
    name: [
        { required: true, message: '请输入物品名称', trigger: 'blur' }
    ],
    description: [
        { required: true, message: '请输入物品描述', trigger: 'blur' }
    ],
    created_by: [
        { required: true, message: '请输入创建人 ID', trigger: 'blur' }
    ]
}

// 获取物品列表
const fetchItemList = async () => {
    loading.value = true
    try {
        const res = await getItemList();
        console.log('res :>> ', res);
        if (res.data.code === 200) {
            itemList.value = res.data.items || [];
        } else {
            console.error('请求成功但返回错误:', res);
            ElMessage.error((res?.data?.message) || '获取物品列表失败');
        }
    } catch (error) {
        console.error('获取物品列表出错:', error);
        ElMessage.error('获取物品列表失败: ' + (error.message || '未知错误'));
    } finally {
        loading.value = false;
    }
}

// 处理编辑
const handleEdit = (row) => {
    editForm.id = row.id
    editForm.name = row.name
    editForm.description = row.description
    editForm.created_by = row.created_by
    dialogVisible.value = true
}

// 提交编辑
const submitEdit = async () => {
    if (!editFormRef.value) return
    
    editFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                console.log('editForm :>> ', editForm);
                const res = await updateItem(editForm)
                console.log('updateItem res :>> ', res);
                
                if (res && res.data && res.data.code === 200) {
                    ElMessage.success('更新物品信息成功')
                    dialogVisible.value = false
                    fetchItemList() // 刷新列表
                } else {
                    ElMessage.error((res?.data?.message) || '更新物品信息失败')
                }
            } catch (error) {
                console.error('更新物品信息出错:', error)
                ElMessage.error('更新物品信息失败: ' + (error.message || '未知错误'))
            }
        } else {
            return false
        }
    })
}

// 处理删除
const handleDelete = (row) => {
    ElMessageBox.confirm(
        `确定要删除 ID 为 "${row.id}" 的物品记录吗？`,
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        try {
            const res = await deleteItem({id:row.id})
            if (res && res.data && res.data.code === 200) {
                ElMessage.success('删除物品记录成功')
                fetchItemList() // 刷新列表
            } else {
                ElMessage.error((res?.data?.message) || '删除物品记录失败')
            }
        } catch (error) {
            console.error('删除物品记录出错:', error)
            ElMessage.error('删除物品记录失败: ' + (error.message || '未知错误'))
        }
    }).catch(() => {
        // 取消删除操作
    })
}

// 处理添加
const handleAdd = () => {
    // 清空添加表单
    Object.keys(addForm).forEach(key => {
        addForm[key] = '';
    });
    addDialogVisible.value = true;
}

// 提交添加
const submitAdd = async () => {
    if (!addFormRef.value) return

    addFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                console.log('addForm :>> ', addForm);
                const res = await addItem(addForm)
                console.log('addItem res :>> ', res);

                if (res && res.data && res.data.code === 200) {
                    ElMessage.success('添加物品成功')
                    addDialogVisible.value = false
                    fetchItemList() // 刷新列表
                } else {
                    ElMessage.error((res?.data?.message) || '添加物品失败')
                }
            } catch (error) {
                console.error('添加物品出错:', error)
                ElMessage.error('添加物品失败: ' + (error.message || '未知错误'))
            }
        } else {
            return false
        }
    })
}

// 页面加载时获取数据
onMounted(() => {
    fetchItemList()
})
</script>

<style scoped>
.content-preview {
    max-height: 100px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
}
</style>